<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>影厅管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
            margin-top: 20px;
        }

        .seat-selection {
            max-width: 600px;
            margin: 50px auto;
        }

        .seat-row {
            display: flex;
            justify-content: space-around;
            margin-bottom: 10px;
        }

        .seat {
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            cursor: pointer;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgb(64, 158, 255);
            color: white;
        }

        .seat i {
            margin-right: 5px;
        }

        .modal-content {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .el-table .el-button {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="搜索影厅名称" v-model="searchKeyword" style="width: 200px;"
                      @input="fetchHalls"></el-input>
            <el-button type="primary" size="small" @click="handleAddHall">添加影厅</el-button>
        </div>
        <el-table :data="halls" stripe>
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="name" label="影厅名称"></el-table-column>
            <el-table-column prop="cinemaId" label="所属影院ID"></el-table-column>
            <el-table-column prop="seatsLayout" label="座位布局">
                <template slot-scope="scope">
                    <div v-if="scope.row.seatsLayout" class="seat-selection">
                        <div v-for="(row, rowIndex) in JSON.parse(scope.row.seatsLayout)" :key="rowIndex" class="seat-row">
                            <div v-for="(seat, seatIndex) in row" :key="seatIndex" class="seat">
                                <i class="el-icon-potato-strips"></i>
                            </div>
                        </div>
                    </div>
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
                    <el-button @click="openSeatLayoutModal(scope.row)" type="info" size="small">设置座位布局</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalHalls">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog :title="isEditMode ? '编辑影厅' : '添加影厅'" :visible.sync="dialogVisible">
        <el-form :model="currentHall" :rules="rules" ref="hallForm" label-width="100px">
            <el-form-item label="影厅名称" prop="name">
                <el-input v-model="currentHall.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="所属影院" prop="cinemaId">
                <el-select v-model="currentHall.cinemaId" placeholder="请选择影院" @change="fetchCinemas">
                    <el-option
                            v-for="cinema in cinemas"
                            :key="cinema.id"
                            :label="cinema.name"
                            :value="cinema.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
    </el-dialog>

    <!-- 座位布局模态框开始 -->
    <el-dialog
            title="设置座位布局"
            :visible.sync="seatLayoutModalVisible"
            width="60%"
            :before-close="handleSeatLayoutModalClose"
    >
        <div class="modal-content">
            <el-form :model="seatLayoutForm" :rules="seatLayoutRules" ref="seatLayoutForm" label-width="100px">
                <el-form-item label="行数" prop="rows">
                    <el-input v-model.number="seatLayoutForm.rows" placeholder="请输入行数"></el-input>
                </el-form-item>
                <el-form-item label="列数" prop="cols">
                    <el-input v-model.number="seatLayoutForm.cols" placeholder="请输入列数"></el-input>
                </el-form-item>
            </el-form>
            <div v-if="seatLayoutForm.rows && seatLayoutForm.cols" class="seat-selection">
                <div v-for="row in seatLayoutForm.rows" :key="row" class="seat-row">
                    <div v-for="col in seatLayoutForm.cols" :key="col" class="seat">
                        <i class="el-icon-potato-strips"></i>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <el-button type="primary" size="small" @click="saveSeatLayout">保存设置</el-button>
        </div>
    </el-dialog>
    <!-- 座位布局模态框结束 -->
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                halls: [],
                totalHalls: 0,
                pageSize: 5,
                currentPage: 1,
                dialogVisible: false,
                currentHall: {},
                isEditMode: false,
                cinemas: [],
                rules: {
                    name: [
                        {required: true, message: '请输入影厅名称', trigger: 'blur'}
                    ],
                    cinemaId: [
                        {required: true, message: '请选择所属影院', trigger: 'change'}
                    ]
                },
                seatLayoutModalVisible: false,
                seatLayoutForm: {
                    rows: 1,
                    cols: 1
                },
                seatLayoutRules: {
                    rows: [
                        {required: true, message: '请输入行数', trigger: 'blur'},
                        {type: 'number', min: 1, max: 7, message: '行数必须在1到7之间', trigger: 'blur'}
                    ],
                    cols: [
                        {required: true, message: '请输入列数', trigger: 'blur'},
                        {type: 'number', min: 1, max: 7, message: '列数必须在1到7之间', trigger: 'blur'}
                    ]
                },
                currentSeatLayout: null
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1; // 重置当前页码为1
                    this.fetchHalls(); // 重新获取影厅数据
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchHalls(); // 重新获取影厅数据
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchHalls(); // 重新获取影厅数据
                }
            }
        },
        methods: {
            fetchHalls() {
                axios.get('/hall?operation=findHallsByPageAndName', {
                    params: {
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.halls = data.data; // 更新数据字段为 data.data
                        this.totalHalls = data.total;
                    } else {
                        this.$message.error('获取影厅列表失败');
                    }
                }).catch(error => {
                    console.error('获取影厅列表失败:', error);
                    this.$message.error('获取影厅列表失败');
                });
            },
            fetchCinemas() {
                axios.get('/cinema?operation=getAllCinemas').then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.cinemas = data;
                    } else {
                        this.$message.error('获取影院列表失败');
                    }
                }).catch(error => {
                    console.error('获取影院列表失败:', error);
                    this.$message.error('获取影院列表失败');
                });
            },
            handleAddHall() {
                this.isEditMode = false;
                this.currentHall = {};
                this.fetchCinemas(); // 获取影院列表
                this.dialogVisible = true;
            },
            handleEdit(hall) {
                this.isEditMode = true;
                this.currentHall = Object.assign({}, hall);
                this.fetchCinemas(); // 获取影院列表
                this.dialogVisible = true;
            },
            handleSave() {
                this.$refs.hallForm.validate(valid => {
                    if (valid) {
                        const url = this.isEditMode ? '/hall?operation=updateHall' : '/hall?operation=addHall';
                        axios.post(url, this.currentHall)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success(this.isEditMode ? '影厅信息更新成功' : '影厅添加成功');
                                    this.fetchHalls();
                                } else {
                                    this.$message.error(this.isEditMode ? '影厅信息更新失败' : '影厅添加失败');
                                }
                            })
                            .catch(error => {
                                console.error(this.isEditMode ? '影厅信息更新失败:' : '影厅添加失败:', error);
                                this.$message.error(this.isEditMode ? '影厅信息更新失败' : '影厅添加失败');
                            });
                        this.dialogVisible = false;
                    }
                });
            },
            handleDelete(hall) {
                this.$confirm('此操作将永久删除该影厅, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/hall?operation=deleteHall&id=' + hall.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('影厅删除成功');
                                this.fetchHalls();
                            } else {
                                this.$message.error('影厅删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('影厅删除失败:', error);
                            this.$message.error('影厅删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            openSeatLayoutModal(hall) {
                this.currentSeatLayout = hall;
                if (hall.seatsLayout) {
                    const layout = JSON.parse(hall.seatsLayout);
                    this.seatLayoutForm.rows = layout.length;
                    this.seatLayoutForm.cols = layout[0].length;
                } else {
                    this.seatLayoutForm.rows = 1;
                    this.seatLayoutForm.cols = 1;
                }
                this.seatLayoutModalVisible = true;
            },
            saveSeatLayout() {
                this.$refs.seatLayoutForm.validate(valid => {
                    if (valid) {
                        const seatLayout = [];
                        for (let row = 1; row <= this.seatLayoutForm.rows; row++) {
                            const rowSeats = [];
                            for (let col = 1; col <= this.seatLayoutForm.cols; col++) {
                                rowSeats.push({ row, col });
                            }
                            seatLayout.push(rowSeats);
                        }
                        this.currentSeatLayout.seatsLayout = JSON.stringify(seatLayout);

                        // 更新当前影厅的座位布局
                        axios.post('/hall?operation=updateHall', this.currentSeatLayout)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success('座位布局设置成功');
                                    this.fetchHalls(); // 重新获取影厅列表以更新表格数据
                                } else {
                                    this.$message.error('座位布局设置失败');
                                }
                            })
                            .catch(error => {
                                console.error('座位布局设置失败:', error);
                                this.$message.error('座位布局设置失败');
                            });

                        this.seatLayoutModalVisible = false;
                    }
                });
            },
            handleSeatLayoutModalClose(done) {
                done();
            }
        },
        mounted() {
            this.fetchHalls();
        }
    });
</script>

</body>
</html>